// pages/personal/myorder/detail/detail.js
import { orderDetails, cancelOrder, payOrder, confirmReceipt } from '../../../../../config/config'
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    imgUrl: getApp().globalData.imgUrl,
    refundGoogs: [
      {value: '8685', name: '美国'},
      {value: '6666', name: '中国', checked: 'true'}
    ],
    detailData: [],
    option: {},
    options: null,
    status: '',
    splitStatus: '',
    subOrderInfo: {}, // 子单物流信息
    orderNo: '',
    phoneNumber: '15708447808',
    cancelOrder: false,
    cancelOrderId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {  
    if (options) {
      this.setData({
        options: options
      })
      let option = JSON.parse(decodeURIComponent(options.option))
      this.getorderDetails(option.id)
      this.setData({
        option: option
      })
    }
  },
  // 获取订单详情
  getorderDetails(id) {
    let that = this
    let params = {
      orderId: id
    }
    app.reqFun.requestJson('POST',orderDetails,params,(res)=>{
      if(res.data.success === 1) {
        let detailData = res.data.data
        let orderId = that.data.option.orderId
        let newdetailsListDtos = []
        let newChild = {}
        let subOrderInfo = {}
        for(var i = 0, len = detailData.detailsListDtos.length; i < len; i++) {
          if (detailData.detailsListDtos[i].orderId == orderId) {
            newChild = detailData.detailsListDtos[i]
            subOrderInfo.logisticsMethod = detailData.detailsListDtos[i].logisticsMethod
            subOrderInfo.distributionMode = detailData.detailsListDtos[i].distributionMode
            subOrderInfo.sendPackCoverCharge = detailData.detailsListDtos[i].sendPackCoverCharge
            subOrderInfo.freight = detailData.detailsListDtos[i].freight
          }
        }
        newdetailsListDtos.push(newChild)
        if (orderId) {
          console.log('子单')
          detailData.detailsListDtos = newdetailsListDtos
          that.setData({
            subOrderInfo: subOrderInfo,
            status: detailData.detailsListDtos[0].status,
            orderNo: detailData.detailsListDtos[0].orderNo
          })
        } else {
          if (detailData.splitStatus == '1') {
            //父单已取消作则返回列表
            that.setData({
              jumpToOrderListTip: "订单已取消，点击返回列表",
              jumpToOrderListFlag: true
            })
          }
          if (detailData.splitStatus == '2') {
            //父单已支付则返回列表
            that.setData({
              jumpToOrderListTip: "订单已支付，点击返回列表",
              jumpToOrderListFlag: true
            })
          }
          that.setData({
            splitStatus: detailData.splitStatus,
            orderNo: detailData.orderNo
          })
        }
        that.setData({
          detailData: detailData
        })
      }
    })
  },
  jumpToOrderList() {
    this.setData({ jumpToOrderListFlag: false })
    wx.navigateTo({
      url: '/packagMy/pages/personal/myOrder/myOrder'
    })
  },
  // 申请退款
  applyRefund(e) {
    let orderId = e.currentTarget.dataset.data.orderId
    let orderItemId = e.currentTarget.dataset.data.orderItemId
    let option = {
      orderId: orderId,
      orderItemId: orderItemId
    }
    wx.navigateTo({
      url: '../../myOrder/applyRefund/applyRefund?option=' + JSON.stringify(option)
    })
  },
  refundDetail(e) {
    let id = e.currentTarget.dataset.data.refundId
    wx.navigateTo({
      url: '../../myOrder/refundDetail/refundDetail?id=' + id
    })
  },
  // 取消订单
  orderCancel(e) {
    let orderId = e.currentTarget.dataset.data
    let that = this
  
    that.setData({
      cancelOrder: true,
      cancelOrderId: orderId
    })
  },
  cancelOrder() {
    let cancelOrderId = this.data.cancelOrderId
    let params = {
      orderId: cancelOrderId
    }
    app.reqFun.requestJson('POST',cancelOrder,params,(res)=>{
      if(res.data.success === 1) {
         wx.navigateTo({
           url: '/packagMy/pages/personal/myOrder/myOrder',
         })
      }
    })
  },
  onClose() {
    this.setData({ cancelOrder: false });
  },
  // 立即支付
  payOrder(e){
    let orderId = e.currentTarget.dataset.orderid
    let orderNo = e.currentTarget.dataset.orderno
    let orderType = e.currentTarget.dataset.ordertype
    let that=this
    let parms={
      orderNo:orderNo,
      paymentType:'SMALL_PROGRAM'
    }
    app.reqFun.requestJson('POST',payOrder,parms,(res)=>{
      if(res.data.success==1){
        var payData=res.data.data
        that.setData({
          payData:payData
        })
        that.watchPay(payData, orderType, orderId)
      }else{
        wx.showToast({
          title: '发起支付订单失败。',
          icon:'none'
        })
      }
    })
  },
  watchPay(payData, orderType, orderId){
    var that=this;
    wx.requestPayment({
      timeStamp: payData.timeStamp,
      nonceStr: payData.nonceStr,
      package: payData.packageValue,
      signType: payData.signType,
      paySign: payData.paySign,
      success (res) {
        if (orderType === 2 || orderType === 3) {
          app.couponNotifySubscribe(()=>{
            wx.redirectTo({
              url: '/packagBuy/pages/paySuccess/paySuccess?type=success',
            })
          }, orderId)
        } else {
          app.moreOrderNotifySubscribe(()=>{
            wx.redirectTo({
              url: '/packagBuy/pages/paySuccess/paySuccess?type=success',
            })
          }, orderId, orderType)
        }
      },
      fail (res) {
        wx.showModal({
          title: '支付失败',
          content: '支付失败,是否重新支付？',
          success (res) {
            if (res.confirm) {
              that.watchPay(payData, orderType, orderId)
            } else if (res.cancel) {
              wx.redirectTo({
                url: '/packagBuy/pages/paySuccess/paySuccess??type=err',
              })
            }
          }
        })
      }
    })
  },
  // 确认收货
  confirmReceipt(e) {
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否确认收货？',
      success (res) {
        if (res.confirm) {
          let orderNo = e.currentTarget.dataset.data
          console.log('orderNo', orderNo)
          let params = {
            orderNo: orderNo
          }
          app.reqFun.requestJson('POST',confirmReceipt,params,(res)=>{
            if(res.data.success === 1) {
              let options = that.options
              let option = JSON.parse(decodeURIComponent(options.option))
              option.status = '6'
              options.option = JSON.stringify(option)
              that.onLoad(that.options)
            } else {
              wx.showToast({
                title: res.data.msg,
                icon:'none'
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  applyRefundModle() {
    this.setData({
      show: true
    })
  },
  // 关闭弹框
  onCloseModel() {
    this.setData({
      show: false
    })
  },
  // 多选框改变事件
  checkboxChange(e) {
    // console.log('e', e.detail.value)
  },
  goreBack(e){
    wx.navigateBack({
      delta: 1,
    })
  },
  goHome: function (e) { //返回主页
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  goGoodsinfo(e) {
    let skuid = e.currentTarget.dataset.data
      wx.navigateTo({
          url: '/packageShop/pages/goodsInfo/goodsInfo?id=' + skuid,
      })
  },
  phoneCall(e) {
    // let that = this
    let phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  groupDetail(e) {
    let groupid = this.data.detailData.detailsListDtos[0].spellGroupId
    wx.navigateTo({
      url: '/packageLive/pages/spellBuy/detail/detail?id=' + groupid,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})
